<template>
  <div class="user-config">
    <div class="header">

      <van-icon name="arrow-left" class="left" @click="goBack">个人信息</van-icon>

      <p class="right" @click="updateUserMsg">完成</p>
    </div>
    <div class="content">
      <div class="item">
        <div class="left">photo</div>
        <div class="right">
          <van-uploader :before-read="beforeRead">
            <img :src="imgPath" alt="" />
          </van-uploader>
          <van-icon name="arrow" class="icon" @click="viewImg" />
        </div>
      </div>
      <div class="item" v-for="(item, index) in conversionUserMsg">
        <div class="left">
          {{ index }}
        </div>
        <div class="right">
          <input type="text" v-model="conversionUserMsg[index]" :placeholder="item ? item : '还没填写'" />
          <van-icon name="arrow" class="icon" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { Toast, Dialog, ImagePreview } from "vant";
import { useRouter } from "vue-router";
import { submitUpload } from "@/tool/submitUpload.js";
import { ref } from "vue";
import { post } from '@/tool/post'
import { getUserMsg } from "@/tool/getUserMsg.js";
import { deepCopy } from '@/tool/deepCopy.js';
export default {
  setup() {
    const notNeedUserMsgList = ['id', 'userPhoto', 'username']
    const router = useRouter();
    const goBack = () => {
      let tempVal = undefined
      for (let i in userMsgCopy) {
        if (userMsgCopy[i] != conversionUserMsg.value[i]) {
          if ((conversionUserMsg.value[i] === null || conversionUserMsg.value[i] === '') && userMsgCopy[i] === null) { }
          else {
            tempVal = Dialog.confirm({
              width: "220px",
              title: "退出确认",
              showCancelButton: true,
              beforeClose,
              message: "更改数据未保存,确认退出么?",
            }).then(() => {
              router.back(-1)
            })
          }
        }
      }
      if (tempVal === undefined) router.back(-1)
    };
    const conversionUserMsg = ref(getUserMsg()) || null;
    for (let i in conversionUserMsg.value) {
      if (notNeedUserMsgList.indexOf(i) !== -1) {
        delete conversionUserMsg.value[i]
      }
    }
    const beforeClose = (action) => {
      return new Promise((resolve) => {
        if (action === "confirm") {
          resolve(true);
          Dialog.close();
        } else {
          resolve(false);
          Dialog.close();
        }
      });
    }
    const userMsgCopy = deepCopy(conversionUserMsg.value)
    const imgPath = ref(
      `${getUserMsg()?.userPhoto || "http://116.62.149.160:4000/girl.jpg"}`
    );
    const beforeRead = (file) => {
      Toast.loading({
        message: "上传中..",
        duration: 0,
      });
      submitUpload(file).then((res) => {
        imgPath.value = res.data.imgPath;
        setTimeout(() => Toast.clear(), 1000)
      });
      return true;
    };
    const viewImg = () => {
      ImagePreview([imgPath.value])
    };
    const updateUserMsg = () => {
      const result = { ...getUserMsg(), ...conversionUserMsg.value }
      const requestToast = Toast.loading({
        message: '正在修改',
        duration: 1000
      })
      post('/user/updateMsg', { ...getUserMsg(), ...conversionUserMsg.value, userPhoto: imgPath.value }).then((res) => {
        if (res.code === 200) {
          requestToast.clear()
          Toast.success(res.msg)
          const userMsg = JSON.parse(localStorage.getItem(import.meta.env.VITE_APP_USERMSG))
          for (let i in userMsg) {
            userMsg[i] = result[i]
          }
          localStorage.setItem(
            import.meta.env.VITE_APP_USERMSG,
            JSON.stringify({
              ...userMsg,
              userPhoto:imgPath.value,
              oldPassword: null,
              newPassword: null
            })
          );
          setTimeout(router.back(-1), 0)
        }
        requestToast.clear()
      })
    }
    return {
      goBack,
      beforeRead,
      updateUserMsg,
      viewImg,
      imgPath,
      conversionUserMsg,
    };
  },
};
</script>

<style lang="less" scoped>
.user-config {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;

  .header {
    padding: 0 10px;
    margin: 10px auto;
    box-sizing: border-box;
    width: 100%;
    height: 30px;
    line-height: 30px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    span {
      text-align: center;
      margin: 0 auto;
    }

    .right {
      text-align: center;
      color: gray;
    }

    .right:active {
      color: rgb(5, 196, 59);
    }

  }

  .content {
    flex: 1;
    width: 100%;

    .item {
      display: flex;
      justify-content: center;
      align-items: center;
      line-height: 20px;
      min-height: 40px;
      max-height: 70px;
      border-bottom: 1px solid #dbdbdb;

      .left {
        flex: 1;
        margin: 0 20px;
      }

      .right {
        flex: 0 0 120px;
        text-align: right;
        margin: 0 auto;
        display: flex;

        img {
          margin: 5px auto;
          text-align: center;
          border-radius: 50% !important;
          width: 60px;
          padding: 0 20px;
          height: 60px;
        }

        .icon {
          flex: 1 1 30px;
          text-align: center;
          margin: auto auto;
        }

        p {
          width: 100%;
          margin: 0 auto;
        }

        input {
          border: none;
          width: 100%;
        }
      }
    }
  }
}
</style>